<template>
    <div class="marketing_enough_add">
        <el-form label-width="120px" :model="form" :rules="rules" ref="addForm">
            <div class="form_content">
                <el-card class="base_card">
                    <template #header>基础设置</template>
                    <el-row>
                        <el-col>
                            <el-form-item label="活动名称" prop="activityName">
                                <el-input
                                    maxlength="20"
                                    show-word-limit
                                    v-model.trim="form.activityName"
                                    placeholder="请输入活动名称，20个字以内"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item
                                label="活动时间"
                                prop="activityAt"
                                @mouseover="handleMouseover"
                                @mouseleave="handleMouseleave">
                                <el-date-picker
                                    v-model="form.activityAt"
                                    type="datetimerange"
                                    range-separator="至"
                                    :default-time="defaultTime"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    :disabled="isDisabled"
                                    :disabled-date="disabledDate" />
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item label="活动商品" prop="activityGoodType">
                                <el-radio-group
                                    v-model="form.activityGoodType"
                                    @change="goodTypeChange"
                                    @mouseover="handleMouseover"
                                    @mouseleave="handleMouseleave"
                                    :disabled="isDisabled">
                                    <div
                                        class="activity-good-type"
                                        v-for="item in activityGoodTypeCopy"
                                        :key="item.value">
                                        <el-radio :label="item.value">
                                            {{ item.label }}
                                        </el-radio>
                                        <!-- 弹窗 -->
                                        <!-- <ZwChooserGoods
                                            :disabled="isDisabled"
                                            style="margin-left: -14px"
                                            v-if="item.value != 1 && form.activityGoodType == item.value"
                                            :value="form.goodsIds"
                                            :isMulti="true"
                                            @handle-confirm="getGoodData" /> -->
                                        <ZwGeneralGoods
                                            :disabled="isDisabled"
                                            style="margin-left: -14px"
                                            v-if="item.value != 1 && form.activityGoodType == item.value"
                                            :value="form.goodsIds"
                                            :isMulti="true"
                                            :isParticipationCol="true"
                                            @handle-confirm="getGoodData"></ZwGeneralGoods>
                                        <!-- <SelectedGoods
                                            @mouseover.stop
                                            @mouseleave.stop
                                            v-if="item.value != 1 && form.activityGoodType == item.value"
                                            :disabled="isDisabled"
                                            :value="form.goodsIds"
                                            @handle-remove="handleRemoveGood"></SelectedGoods> -->
                                        <ZwSelectedGoods
                                            @mouseover.stop
                                            @mouseleave.stop
                                            v-if="item.value != 1 && form.activityGoodType == item.value"
                                            :disabled="isDisabled"
                                            :value="form.goodsIds"
                                            :isParticipationCol="true"
                                            :customTitle="item.value == 2 ? '以下商品参加' : '以下商品不参加'"
                                            @handle-remove="handleRemoveGood"></ZwSelectedGoods>
                                    </div>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
                <el-card class="last-card">
                    <template #header>优惠设置</template>
                    <el-row>
                        <el-col>
                            <el-form-item
                                v-for="{ label, checkboxLabel, prop, tip } in advancedList"
                                :label="label"
                                :prop="prop == 'reduce' ? '' : prop"
                                :required="prop == 'reduce'"
                                :key="label">
                                <div class="order-amount" v-if="prop === 'reduce'">
                                    单笔订单活动商品{{ activityType == 7 ? '金额' : '件数' }}满
                                    <el-form-item prop="discountSet.orderAmount">
                                        <el-input-number
                                            :disabled="isDisabled"
                                            v-model="form.discountSet.orderAmount"
                                            class="custom-discount-number"
                                            :min="activityType == 7 ? 0.01 : 1"
                                            :max="activityType == 7 ? 99999.99 : 99"
                                            :controls="false"
                                            @mouseover="handleMouseover"
                                            @mouseleave="handleMouseleave"
                                            :precision="activityType == 7 ? 2 : 0"
                                            @blur="validateField('discountSet.reduce')"
                                            placeholder="请输入"></el-input-number
                                        >{{ activityType == 7 ? '元' : '件' }}</el-form-item
                                    >，{{ activityType == 7 ? '减' : '打' }}
                                    <el-form-item prop="discountSet.reduce">
                                        <el-input-number
                                            :disabled="isDisabled"
                                            v-model="form.discountSet.reduce"
                                            class="custom-discount-number"
                                            :min="activityType == 7 ? 0.01 : 0.1"
                                            :max="activityType == 7 ? 99999.99 : 9.9"
                                            :controls="false"
                                            @mouseover="handleMouseover"
                                            @mouseleave="handleMouseleave"
                                            @blur="validateField('discountSet.orderAmount')"
                                            :precision="activityType == 7 ? 2 : 1"
                                            :placeholder="
                                                activityType == 7 ? '支持小数点后2位' : '支持小数点后1位'
                                            "></el-input-number></el-form-item
                                    >{{ activityType == 7 ? '元' : '折' }}
                                </div>
                                <el-checkbox
                                    v-else
                                    v-model="form.discountSet[prop]"
                                    :true-label="2"
                                    :false-label="1"
                                    :disabled="isDisabled"
                                    @mouseover="handleMouseover"
                                    @mouseleave="handleMouseleave"
                                    >{{ checkboxLabel }}</el-checkbox
                                >
                                <div v-if="tip" class="custom-tip" v-html="tip"></div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
            </div>
            <div class="form-footer">
                <div>
                    <el-button @click="cancelHandler">取消</el-button>
                    <el-button type="primary" @click="saveHandler">保存</el-button>
                </div>
            </div>
        </el-form>
        <!-- tooltip提示框 -->
        <el-tooltip
            popper-class="custom-tooltip-class"
            v-model:visible="tooltipVisible"
            content="活动已开始，不支持编辑"
            placement="top"
            trigger="click"
            virtual-triggering
            :virtual-ref="triggerRef" />
        <!-- 弹窗 -->
        <ConflictDialog ref="conflictDialog"></ConflictDialog>
    </div>
</template>

<script setup>
import { ref, unref, reactive, computed, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import request from '@/request/index';
import constants from '@/commons/constants';
import { ElMessage } from 'element-plus';
import { isDayBefore, cloneDeep, format, packSelectObjUtil } from '@/commons/utils';
import { setLayout, resetLayout } from '@/hooks/layout';
import ConflictDialog from './conflictDialog.vue';

const activityGoodType = reactive(packSelectObjUtil(constants.ACTIVITY_GOOD_TYPE));
const activityGoodTypeCopy = [activityGoodType[1], activityGoodType[2], activityGoodType[0]];

const router = useRouter();
const route = useRoute();

const isPageLoading = ref(false);
const conflictDialog = ref(null);
const addForm = ref(null);
const position = ref({
    top: 0,
    left: 0,
    bottom: 0,
    right: 0
});
const triggerRef = ref({
    getBoundingClientRect() {
        return position.value;
    }
});
let tooltipVisible = ref(false);

const form = reactive({
    activityName: null, //活动名称
    activityAt: [], //活动开始时间
    activityGoodType: 2, //1 是全部商品 2 是指定商品参加 3 指定商品不参加
    goodsIds: [], //activityGoodType 除了1 必填 商品ID数组
    activityType: 7, //7,满x元减 8 满x件折
    discountSet: {
        orderAmount: null, //activityType = 7 满几元（分）  8时满几件
        reduce: null, //activityType = 7 减几元（分）  8时打折（都乘以 10）
        discountRepeat: 1, //1 不允许叠加使用优惠群 2允许使用
        fullReduceMail: 1 //1 不允许满减包邮 2允许使用
    } //优惠设置对象
});

const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)];
const disabledDate = date => {
    return isDayBefore(date);
};
const advancedList = [
    { label: '优惠规则', prop: 'reduce' },
    { label: '优惠叠加', checkboxLabel: '允许叠加使用优惠券', prop: 'discountRepeat' },
    { label: '满减包邮', checkboxLabel: '开启满减包邮', prop: 'fullReduceMail' }
];

const checkGoods = (rule, value, callback) => {
    if ([2, 3].includes(form.activityGoodType) && !form.goodsIds?.length) {
        return callback(new Error(`指定商品${form.activityGoodType == 3 ? '不' : ''}参加，必须选择商品`));
    }
    callback();
};
const checkActivityAt = (rule, value, callback) => {
    if (!value || !value[0]) {
        return callback(new Error('请选择活动时间'));
    }
    if (value) {
        const currentDate = new Date();
        if (value[0] < currentDate) {
            return callback(new Error('活动时间不能早于当前时间'));
        }
    }
    callback();
};

const checkOrderAmount = (rule, value, callback) => {
    if (activityType.value == 7) {
        if (!value) {
            return callback(new Error('请输入0.01~99999.99的数值'));
        }
        if (value < 0.01 || value > 99999.99) {
            return callback(new Error('请输入0.01~99999.99的数值'));
        }
        if (value <= form.discountSet.reduce) {
            return callback(new Error('商品门槛金额需大于减免金额'));
        }
        return callback();
    }
    if (!value) {
        return callback(new Error('请输入1~99的数值'));
    }
    if (value < 1 || value > 99) {
        return callback(new Error('请输入1~99的数值'));
    }
    callback();
};

const checkReduce = (rule, value, callback) => {
    if (activityType.value == 7) {
        if (!value) {
            return callback(new Error('请输入0.01~99999.99的数值'));
        }
        if (value < 0.01 || value > 99999.99) {
            return callback(new Error('请输入0.01~99999.99的数值'));
        }
        if (value >= form.discountSet.orderAmount) {
            return callback(new Error('减免金额需小于商品门槛金额'));
        }
        return callback();
    }
    if (!value) {
        return callback(new Error('请输入0.1~9.9的数值'));
    }
    if (value < 0.1 || value > 9.9) {
        return callback(new Error('请输入0.1~9.9的数值'));
    }
    callback();
};

const rules = computed(() => {
    const baseRuleList = {
        activityName: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
            { max: 20, message: '最长不超过20个字', trigger: 'blur' }
        ],
        activityAt: [{ required: true, trigger: 'change', validator: checkActivityAt }],
        activityGoodType: [{ required: true, validator: checkGoods, trigger: 'blur' }],
        'discountSet.orderAmount': [{ required: true, validator: checkOrderAmount, trigger: 'blur' }],
        'discountSet.reduce': [{ required: true, validator: checkReduce, trigger: 'blur' }]
    };
    return { ...baseRuleList };
});

const isDisabled = computed(() => {
    const realStatus = form?.activityStatusName?.realStatus;
    return realStatus && realStatus != 1;
});
const id = computed(() => {
    return route?.query?.id;
});
const activityType = computed(() => {
    const path = route?.path;
    if (/yuan/.test(path)) {
        return 7;
    }
    if (/piece/.test(path)) {
        return 8;
    }
    return 7;
});

const cancelHandler = () => {
    router.back();
};
const clearValidate = field => {
    unref(addForm).clearValidate(field);
};
const validateField = field => {
    unref(addForm).validateField(field);
};
const getGoodData = data => {
    form.goodsIds.length = 0;
    Object.assign(form.goodsIds, cloneDeep(data));
    validateField('activityGoodType');
};
const handleRemoveGood = id => {
    form.goodsIds.splice(form.goodsIds.indexOf(id), 1);
};

const goodTypeChange = val => {
    if (val == 1) {
        form.goodsIds.length = 0;
    }
    validateField('activityGoodType');
};
const handleMouseover = e => {
    if (!isDisabled.value) {
        return;
    }
    tooltipVisible.value = true;
    position.value = DOMRect.fromRect({
        width: 0,
        height: 0,
        x: e.clientX,
        y: e.clientY
    });
};
const handleMouseleave = el => {
    if (!isDisabled.value) {
        return;
    }
    tooltipVisible.value = false;
    position.value = {
        top: 0,
        left: 0,
        bottom: 0,
        right: 0
    };
};
// 新增/编辑表单
const saveHandler = async () => {
    if (unref(isPageLoading)) return;
    isPageLoading.value = true;
    if (!unref(addForm)) return;
    await unref(addForm).validate(async (valid, fields) => {
        if (valid) {
            const _form = cloneDeep(form);
            _form.activityType = activityType.value;
            _form.activityStartTime = format(_form.activityAt[0], 'YYYY-MM-DD HH:mm:ss');
            _form.activityEndTime = format(_form.activityAt[1], 'YYYY-MM-DD HH:mm:ss');
            delete _form.activityAt;
            if (_form.activityType == 7) {
                _form.discountSet.orderAmount = Math.round(_form.discountSet.orderAmount * 100);
                _form.discountSet.reduce = Math.round(_form.discountSet.reduce * 100);
            } else {
                _form.discountSet.reduce = Math.round(_form.discountSet.reduce * 10);
            }
            // 是否冲突验证
            if (await conflictDialog?.value?.checkConflictVisible(_form)) {
                isPageLoading.value = false;
                return;
            }
            try {
                const { code } = await request(`fullreduce${unref(id) ? 'Update' : 'Create'}`, _form);
                if (code !== 0) {
                    isPageLoading.value = false;
                    return;
                }
            } catch (error) {
                isPageLoading.value = false;
            }
            isPageLoading.value = false;
            ElMessage({
                type: 'success',
                message: '满减活动保存成功'
            });
            cancelHandler();
        } else {
            isPageLoading.value = false;
            unref(addForm).scrollToField(Object.keys(fields)?.[0]);
        }
    });
};

const getDetail = async () => {
    if (unref(id)) {
        const { data } = await request('fullreduceInfo', { id: unref(id) });
        data.activityAt = [data.activityStartTime, data.activityEndTime];
        if (data.activityType == 7) {
            data.discountSet.orderAmount = data.discountSet.orderAmount / 100;
            data.discountSet.reduce = data.discountSet.reduce / 100;
        } else {
            data.discountSet.reduce = data.discountSet.reduce / 10;
        }
        Object.assign(form, data);
    }
};

onMounted(() => {
    getDetail();
    setLayout();
});
onUnmounted(() => {
    resetLayout();
});
</script>

<style lang="scss">
@import './scss/global.scss';
</style>
<style lang="scss" scoped>
@import './scss/scope.scss';
</style>
